<script setup lang="ts">
import 'virtual:windi.css'


/**
 * 是否开启拦截
 */
const openInterceptor = true;
/**
 * 要拦截的 url
 */
const catchUrls: string[] = [
  'https://space.bilibili.com/ajax/settings/getSettings?mid=329519036'
];

const code = `
localStorage.setItem('young-plugin', '[12138, 9527]')
console.log("🚀 ~ file: App.vue ~ line 19 ~ storageDemo", ${localStorage.length})

const ajaxInterceptor_switchOn = ${openInterceptor};
const ajaxInterceptor_rules = ${JSON.stringify(catchUrls)};

const ajax_interceptor_qoweifjqon = {
  originalXHR: window.XMLHttpRequest,
  myXHR: function() {
    let pageScriptEventDispatched = false;
    const modifyResponse = () => {
      ajaxInterceptor_rules.forEach((url) => {
        let matched = false;
        if (this.responseURL.indexOf(url) > -1) {
          matched = true;
        }
        if (matched) {
          try {
            const res = JSON.parse(this.response);
            console.log("🚀 ~ file: App.vue ~ line 36 ~ ajaxInterceptor_rules.forEach ~ res", res)
          } catch {}
        }
      })
    }
    
    const xhr = new ajax_interceptor_qoweifjqon.originalXHR;
    for (let attr in xhr) {
      if (attr === 'onreadystatechange') {
        xhr.onreadystatechange = (...args) => {
          if (this.readyState == 4 && ajaxInterceptor_switchOn) {
            // 数据拦截
            modifyResponse();
          }
          this.onreadystatechange && this.onreadystatechange.apply(this, args);
        }
        continue;
      } else if (attr === 'onload') {
        xhr.onload = (...args) => {
          // 数据拦截
          modifyResponse();
          this.onload && this.onload.apply(this, args);
        }
        continue;
      }
  
      if (typeof xhr[attr] === 'function') {
        this[attr] = xhr[attr].bind(xhr);
      } else {
        // responseText和response不是writeable的，但拦截时需要修改它，所以修改就存储在this[\`_\${attr}\`]上
        if (attr === 'responseText' || attr === 'response') {
          Object.defineProperty(this, attr, {
            get: () => this[\`_\${attr}\`] == undefined ? xhr[attr] : this[\`_\${attr}\`],
            set: (val) => this[\`_\${attr}\`] = val,
            enumerable: true
          });
        } else {
          Object.defineProperty(this, attr, {
            get: () => xhr[attr],
            set: (val) => xhr[attr] = val,
            enumerable: true
          });
        }
      }
    }
  },

  originalFetch: window.fetch.bind(window),
  myFetch: function(...args) {
    console.log("🚀 ~ file: interceptor.ts ~ line 85 ~ args", args)
    return ajax_interceptor_qoweifjqon.originalFetch(...args).then((response) => {
      ajaxInterceptor_rules.forEach((url) => {
        let matched = false;
        if (ajaxInterceptor_switchOn && response.url.indexOf(url) > -1) {
          matched = true;
        }

        if (matched) {
          try {
            const res = JSON.parse(this.response);
            console.log("🚀 ~ file: App.vue ~ line 36 ~ ajaxInterceptor_rules.forEach ~ res", res)
          } catch {}
        }
      });

      return response;
    });
  },
}

console.log('XHR 托管')
window.XMLHttpRequest = ajax_interceptor_qoweifjqon.myXHR;
window.fetch = ajax_interceptor_qoweifjqon.myFetch;`;

const src = window.URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
const script = document.createElement('script');
script.src = src;
document.body.appendChild(script)

/**
 * 获取拦截到的数据
 */
const getData = () => {
  const res = localStorage.getItem('young-plugin');
  console.log("🚀 ~ file: App.vue ~ line 118 ~ getData ~ res", res)
}
</script>

<template>
  <div class="fixed right-0 bottom-0 m-5 z-100 flex font-sans select-none leading-1em">
    <div
      class="bg-white text-gray-800 rounded-full shadow w-max h-min"
      p="x-4 y-2"
      m="y-auto r-2"
      transition="opacity duration-300"
    >
      Vitesse WebExt
    </div>
    <div
      class="flex w-10 h-10 rounded-full shadow cursor-pointer"
      bg="teal-600 hover:teal-700"
      @click="getData"
    >
      <pixelarticons-power class="block m-auto text-white text-lg" />
    </div>
  </div>
</template>
